<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\adminapi\controller;

/**
 * 管理员用户控制器
 */

use app\adminapi\service\AdminTokenService;
use app\common\model\AdminRule;
use app\common\service\Utils;
use app\common\validate\AdminValidate;
use think\facade\Db;
use app\common\model\Admin as AdminModel;
use app\common\model\User as UserModel;

class User extends BaseAdmin
{

    protected $dataModel = UserModel::class;
    protected array $allowSearch = ['nickname', 'is_disable']; //搜索器

    //管理员登录
    public function login()
    {
        $params = (new AdminValidate())->post()->goCheck();

        $user = AdminModel::where($params)->findOrEmpty();
        $user->hidden(['password', 'root', 'login_ip', 'group_id']);
        if ($user->isEmpty()) {
            return $this->fail('用户名或密码错误！');
        }

        $user->login_ip = request()->ip();
        $user->login_time = time();

        $user->save();

        $userSession = AdminTokenService::setToken($user->id);

        $user->token = $userSession["token"];
        return $this->data($user);
    }

    //登录用户菜单权限
    public function menuList()
    {

        $userId = $this->adminId;
        $user = AdminModel::where("id", $userId)->find();

        if ($user["root"] == 1) {
            $accountRule = Db::name("admin_rule")->where("type", 1)->select();
        } else {
            $ruleIds = Db::name("admin_group_rule")->where("group_id", $user["group_id"])->column("rule_id");
            $accountRule = Db::name("admin_rule")->where("type", 1)->where("id", "in", $ruleIds)->select();
        }

        $treeRule = Utils::makeTree($accountRule);

        return $this->data($treeRule);
    }

    //删除管理员
    public function delAdmin()
    {
        $userId = input("user_id");

        $res = AdminModel::where("id", $userId)->delete();

        if ($res) {
            return $this->success("删除成功");
        }

        return $this->fail("删除失败");
    }

    //角色列表
    public function roleList()
    {
        $list = Db::name("admin_group")->select();
        return $this->data($list);
    }

    //管理员列表
    public function adminList()
    {
        $list = AdminModel::select()->each(function ($item) {
            if ($item["root"] == 1) {
                $item["group_name"] = '系统管理员';
            } else {
                $item["group_name"] = Db::name("admin_group")->where("id", $item["group_id"])->value("name");
            }
        });

        return $this->data($list);
    }

    //保存管理员
    public function save()
    {
        $data = input("post.");
        $userId = input("id");

        if ($userId) {
            $user = AdminModel::update($data);
        } else {
            $user = AdminModel::create($data);
        }

        if ($user) {
            return $this->data($user, "保存成功");
        }

        return $this->fail("保存失败");
    }

    //角色权限列表
    public function roleRuleList()
    {
        $id = input("id");

        $ruleUserIds = Db::name("admin_group_rule")->where("group_id", $id)->column("rule_id");
        $ruleAll = Db::name("admin_rule")->select()->each(function ($item, $key) use ($ruleUserIds) {
            if (in_array($item["id"], $ruleUserIds)) {
                $item["is_own"] = true;
            } else {
                $item["is_own"] = false;
            }

            return $item;
        });
        $treeRule["all_rule"] = Utils::makeTree($ruleAll);
        $treeRule["user_rule_ids"] = $ruleUserIds;
        return $this->data($treeRule);
    }

    //角色权限列表
    public function ruleListAll()
    {
        $ruleAll = Db::name("admin_rule")->select();
        $treeRule = Utils::makeTree($ruleAll);
        return $this->data($treeRule);
    }

    //保存角色权限
    public function userRoleSave()
    {
        $ruleIds = input("rule_ids");
        $roleId = input("role_id");
        $data = [];

        foreach ($ruleIds as $id) {
            $data[] = ["group_id" => $roleId, "rule_id" => $id];
        }

        Db::name("admin_group_rule")->where("group_id", $roleId)->delete();

        if (!empty($data)) {
            $res = Db::name("admin_group_rule")->insertAll($data);
            if ($res) {
                return $this->success("保存成功");
            }
            return $this->fail("保存失败");
        } else {
            return $this->success("保存成功");
        }
    }

    //添加角色
    public function roleAdd()
    {
        $data = input("post.");
        $data["create_time"] = time();
        $res = Db::name("admin_group")->insert($data);
        if ($res) {
            return $this->success("添加成功");
        }

        return $this->fail("添加失败");
    }

    //删除角色
    public function roleDel()
    {
        $id = input("post.id");
        $res = Db::name("group")->where("group_id", $id)->delete();
        if ($res) {
            return $this->success("删除成功");
        }

        return $this->fail("删除失败");
    }

    //删除权限规则
    public function ruleDelete()
    {
        $userIds = input("rule_ids/a");

        $res = AdminRule::destroy($userIds);

        if ($res) {
            return $this->success('删除成功');
        }

        return $this->fail("删除失败");
    }

    public function ruleSave()
    {
        $data = input("post.");
        $ruleId = input("id");

        if ($ruleId) {
            $res = AdminRule::update($data);
        } else {
            $res = AdminRule::create($data);
        }


        if ($res) {
            return $this->success('保存成功');
        }

        return $this->fail("保存失败");
    }
}